package com.funsport.service;

import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付服务
 */
@Slf4j
@Service
public class WeChatPayService {
    
    @Value("${wechat.mini-program.app-id}")
    private String appId;
    
    @Value("${wechat.pay.mch-id}")
    private String mchId;
    
    @Value("${wechat.pay.api-v3-key}")
    private String apiV3Key;
    
    @Value("${wechat.pay.private-key-path}")
    private String privateKeyPath;
    
    @Value("${wechat.pay.merchant-serial-number}")
    private String merchantSerialNumber;
    
    @Value("${wechat.pay.notify-url}")
    private String notifyUrl;
    
    private Config config;
    private JsapiServiceExtension service;
    
    /**
     * 初始化微信支付配置
     */
    @PostConstruct
    public void init() {
        try {
            // 检查微信支付配置是否完整
            if (privateKeyPath == null || privateKeyPath.trim().isEmpty() || 
                mchId == null || mchId.trim().isEmpty() ||
                apiV3Key == null || apiV3Key.trim().isEmpty() ||
                merchantSerialNumber == null || merchantSerialNumber.trim().isEmpty()) {
                log.warn("微信支付配置不完整，跳过初始化。请配置完整的微信支付参数后重启服务。");
                return;
            }
            
            // 构造配置（使用商户私钥和证书序列号）
            config = new RSAAutoCertificateConfig.Builder()
                .merchantId(mchId)
                .privateKeyFromPath(privateKeyPath)
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3Key)
                .build();
            
            // 构造service
            service = new JsapiServiceExtension.Builder().config(config).build();
            
            log.info("微信支付服务初始化成功");
        } catch (Exception e) {
            log.error("微信支付服务初始化失败: {}", e.getMessage(), e);
            log.warn("微信支付功能暂时不可用，请检查配置文件中的微信支付参数");
        }
    }
    
    /**
     * 创建JSAPI支付订单
     * 
     * @param orderNo 订单号
     * @param amount 金额（元）
     * @param description 商品描述
     * @param openid 用户openid
     * @return 预支付交易会话标识
     */
    public Map<String, String> createJsapiOrder(String orderNo, BigDecimal amount, String description, String openid) {
        try {
            // 金额转换为分
            int totalAmount = amount.multiply(new BigDecimal(100)).intValue();
            
            // 构造请求参数
            PrepayRequest request = new PrepayRequest();
            Amount amountObj = new Amount();
            amountObj.setTotal(totalAmount);
            request.setAmount(amountObj);
            request.setAppid(appId);
            request.setMchid(mchId);
            request.setDescription(description);
            request.setNotifyUrl(notifyUrl);
            request.setOutTradeNo(orderNo);
            
            Payer payer = new Payer();
            payer.setOpenid(openid);
            request.setPayer(payer);
            
            // 调用下单方法，得到应答
            PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
            
            // 组装前端需要的参数
            Map<String, String> result = new HashMap<>();
            result.put("timeStamp", response.getTimeStamp());
            result.put("nonceStr", response.getNonceStr());
            result.put("package", response.getPackageVal());
            result.put("signType", response.getSignType());
            result.put("paySign", response.getPaySign());
            // result.put("prepayId", response.getPrepayId());
            result.put("prepayId", "mock_prepay_id"); // Placeholder
            
            log.info("创建微信支付订单成功: {}", orderNo);
            return result;
            
        } catch (Exception e) {
            log.error("创建微信支付订单失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建支付订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询订单
     */
    public String queryOrder(String orderNo) {
        try {
            // 这里可以调用微信支付的查询接口
            // QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
            // request.setMchid(mchId);
            // request.setOutTradeNo(orderNo);
            // Transaction result = service.queryOrderByOutTradeNo(request);
            
            log.info("查询微信支付订单: {}", orderNo);
            return "SUCCESS";
        } catch (Exception e) {
            log.error("查询微信支付订单失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 申请退款
     */
    public void refund(String orderNo, BigDecimal refundAmount, String reason) {
        try {
            // 这里可以调用微信支付的退款接口
            log.info("申请退款: 订单号={}, 金额={}, 原因={}", orderNo, refundAmount, reason);
            
            // TODO: 实现具体退款逻辑
            
        } catch (Exception e) {
            log.error("申请退款失败: {}", e.getMessage(), e);
            throw new RuntimeException("申请退款失败: " + e.getMessage());
        }
    }
}

